package com.yann.bomb.crud;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.yann.bomb.BaseActivity;
import com.yann.bomb.R;
import com.yann.bomb.crud.bean.Category;
import com.yann.bomb.crud.bean.User;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.datatype.BatchResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by yayun.xia on 2018/11/27
 */
public class CreateActivity extends BaseActivity implements View.OnClickListener {

    private EditText edtName, edtPwd;
    private RadioGroup radioGroup;
    private Button btnAdd, btnCommon, btnLogin, btnBatchAdd;
    private TextView tvLog;

    private User user;

    @Override
    public int intiLayout() {
        return R.layout.activity_create;
    }

    @Override
    public void initView() {
        setTitle("新增Bomb测试");

        edtName = findView(R.id.edt_name);
        edtPwd = findView(R.id.edt_pwd);
        radioGroup = findView(R.id.radioGroup);
        btnAdd = findView(R.id.btn_create);
        btnLogin = findView(R.id.btn_login);
        btnCommon = findView(R.id.btn_common);
        btnBatchAdd = findView(R.id.btn_batch_add);
        tvLog = findView(R.id.tv_log);

        user = new User();

        edtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                user.setUsername(s.toString());
                changeBtnStatus();
            }
        });

        edtPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                user.setPassword(s.toString());
                changeBtnStatus();
            }
        });

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_man) {
                    user.setUserSex(0);
                } else if (checkedId == R.id.rb_woman) {
                    user.setUserSex(1);
                }
            }
        });

        btnAdd.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        btnCommon.setOnClickListener(this);
        btnBatchAdd.setOnClickListener(this);
    }

    @Override
    public void initData() {

    }

    private void changeBtnStatus() {
        if (TextUtils.isEmpty(edtName.getText()) || TextUtils.isEmpty(edtPwd.getText())) {
            btnAdd.setEnabled(false);
            btnLogin.setEnabled(false);
        } else {
            btnAdd.setEnabled(true);
            btnLogin.setEnabled(true);
        }
    }

    /**
     * 新增一个用户
     */
    private void addUserToBmob() {
        user.setEmail("465425854@qq.com");
        user.setUserImage("sadsdsd");
        user.signUp(new SaveListener<User>() {
            @Override
            public void done(User s, BmobException e) {
                if (e == null) {
                    tvLog.setText("账户注册成功：" + s.toString());
                } else {
                    tvLog.setText("BMOB：" + e.toString());
                }
            }
        });
    }

    /**
     * 添加普通表
     */
    private void addCommonTable() {
        Category category = new Category();
        category.setName("football");
        category.setDesc("足球");
        category.setSequence(1);
        category.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    tvLog.setText("新增普通表成功：" + s);
                } else {
                    tvLog.setText("BMOB：" + s.toString());
                }
            }
        });
    }

    private void TestLogin() {
        user.setUsername(edtName.getText().toString());
        user.setPassword(edtPwd.getText().toString());
        user.login(new SaveListener<User>() {

            @Override
            public void done(User bmobUser, BmobException e) {
                if (e == null) {
                    Toast.makeText(CreateActivity.this, "登录成功:", Toast.LENGTH_LONG).show();
                    tvLog.setText("新增普通表成功：" + bmobUser.toString());
                    //通过BmobUser user = BmobUser.getCurrentUser()获取登录成功后的本地用户信息
                    //如果是自定义用户对象MyUser，可通过MyUser user = BmobUser.getCurrentUser(MyUser.class)获取自定义用户信息
                } else {
                    tvLog.setText("BMOB：" + e.toString());
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_create:
                addUserToBmob();
                break;
            case R.id.btn_login:
                TestLogin();
                break;
            case R.id.btn_common:
                addCommonTable();
                break;
            case R.id.btn_batch_add:
                saveBatch();
                break;
            default:
                break;
        }
    }

    /**
     * 新增多条数据
     */
    private void saveBatch() {
        List<BmobObject> categories = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Category category = new Category();
            category.setName("category" + i);
            category.setDesc("类别" + i);
            category.setSequence(i);
            categories.add(category);
        }
        new BmobBatch().insertBatch(categories).doBatch(new QueryListListener<BatchResult>() {
            @Override
            public void done(List<BatchResult> results, BmobException e) {
                if (e == null) {
                    for (int i = 0; i < results.size(); i++) {
                        BatchResult result = results.get(i);
                        BmobException ex = result.getError();
                        if (ex == null) {
                            tvLog.setText("第" + i + "个数据批量添加成功：" + result.getCreatedAt() + "," + result.getObjectId() + "," + result.getUpdatedAt());
                        } else {
                            tvLog.setText("第" + i + "个数据批量添加失败：" + ex.getMessage() + "," + ex.getErrorCode());

                        }
                    }
                } else {
                    tvLog.setText("失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

}
